package com.example.strategy;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 *  提供一个上下文,获取对应支付策略示例，完成支付操作
 * @author liuxm34
 * @since 2025/4/30
 */
@Component
public class PaymentContext {

    /**
     * Spring 会自动将所有 PaymentStrategy 类型的 Bean 放入这个 Map 中
     */
    @Autowired
    private Map<String, PaymentStrategy> paymentStrategies;


    public void executePayment(String paymentType, double amount) {
        PaymentStrategy strategy = paymentStrategies.get(paymentType);
        if (strategy != null) {
            strategy.pay(amount);
        } else {
            throw new IllegalArgumentException("Unknown payment type: " + paymentType);
        }
    }

    /**
     * 获取具体支付策略
     * @param paymentType
     * @return
     */
    public PaymentStrategy getPayment(String paymentType) {
        PaymentStrategy strategy = paymentStrategies.get(paymentType);
        if (strategy == null) {
            throw new IllegalArgumentException("Unknown payment type: " + paymentType);
        }
        return strategy;
    }
}